package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.core.model.User;
import cn.edu.tju.core.utils.ObjectUtils;
import cn.edu.tju.elm.model.Business;
import cn.edu.tju.elm.model.Cart;
import cn.edu.tju.elm.model.DeliveryAddress;
import cn.edu.tju.elm.model.Order;
//import cn.edu.tju.elb.service.OrderService;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.repository.AddressRepository;
import cn.edu.tju.elm.repository.BusinessRepository;
import cn.edu.tju.elm.repository.CartRepository;
import cn.edu.tju.elm.repository.OrderRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/orders")
@Tag(name = "管理订单", description = "对订单进行增删改查")
public class OrderController {
    @Autowired
    private UserService userService;
    @Autowired
    private BusinessRepository businessRepository;
    @Autowired
    private AddressRepository addressRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private CartRepository cartRepository;

//    @Autowired
//    private OrderService ordersService;

    @PostMapping(value = "")
    @Operation(summary = "生成订单",description = "生成该用户在该商铺下购物车的订单，订单金额为0时会创建失败")
    public HttpResult<Order> addOrders(@RequestBody Order order) throws Exception {



            // 获取当前登录用户
            User user = userService.getUserWithAuthorities().get();

            // 验证商家是否存在
            Business business = businessRepository.findById(order.getBusiness().getId())
                    .orElseThrow(() -> new RuntimeException("商家不存在"));

            // 验证配送地址是否存在
            DeliveryAddress deliveryAddress = addressRepository.findById(order.getDeliveryAddress().getId())
                    .orElseThrow(() -> new RuntimeException("配送地址不存在"));

            // 计算购物车总金额
            BigDecimal totalPrice = cartRepository.getCartTotalByUserAndBusiness(user.getId(), business.getId());

            // 验证订单金额是否有效
            if (totalPrice == null || totalPrice.compareTo(BigDecimal.ZERO) <= 0) {
                return HttpResult.failure(ResultCodeEnum.PRICE_NOT_ENOUGH, "订单金额必须大于0");
            }

            // 创建新订单
            Order newOrder = new Order();

            // 初始化订单基本信息（假设ObjectUtils.newObjectDefaultInit方法存在）
            // 如果不存在，可以手动设置创建信息
            newOrder.setCreator(user.getId());
            newOrder.setCreateTime(LocalDateTime.now());
            newOrder.setUpdater(user.getId());
            newOrder.setUpdateTime(LocalDateTime.now());

            // 设置订单业务信息
            newOrder.setOrderDate(LocalDateTime.now());
            newOrder.setOrderState(0); // 0=待支付
            newOrder.setDeliveryAddress(deliveryAddress);
            newOrder.setBusiness(business);
            newOrder.setCustomer(user);
            newOrder.setOrderTotal(totalPrice);

            Order savedOrder = orderRepository.save(newOrder);

            // 可选：创建订单后清空购物车中的相关商品
            // cartRepository.deleteByCustomerIdAndBusinessId(user.getId(), business.getId());

            return HttpResult.success(savedOrder);
    }









//        User user = userService.getUserWithAuthorities().get();
//        Business business = businessRepository.findById(order.getBusiness().getId()).orElse(null);
//        if (business == null) {
//            return HttpResult.failure(ResultCodeEnum.NOT_FOUND);
//        }
//        DeliveryAddress deliveryAddress = addressRepository.findById(order.getDeliveryAddress().getId()).orElse(null);
//        if (deliveryAddress == null) {
//            return HttpResult.failure(ResultCodeEnum.NOT_FOUND);
//        }
//        BigDecimal totalPrice = cartRepository.getCartTotalByUserAndBusiness(user.getId(), business.getId());
//        if (totalPrice == null || totalPrice.compareTo(BigDecimal.ZERO) < 0) {
//            return HttpResult.failure(ResultCodeEnum.PRICE_NOT_ENOUGH);
//        }
//        Order newOrder = new Order();
//        ObjectUtils.newObjectDefaultInit(newOrder, user);
//        newOrder.setOrderDate(order.getOrderDate());
//        newOrder.setOrderState(0);
//        newOrder.setDeliveryAddress(deliveryAddress);
//        newOrder.setBusiness(business);
//        newOrder.setCustomer(user);
//        newOrder.setOrderDate(LocalDateTime.now());
//        newOrder.setOrderTotal(totalPrice);
//        return HttpResult.success(orderRepository.save(newOrder));


    @GetMapping("/{id}")
    @Operation(summary = "根据id查看订单",method = "GET")
    public HttpResult getOrderById(@PathVariable Long id) throws Exception{
        // 获取当前登录用户
        User currentUser = userService.getUserWithAuthorities()
                .orElseThrow(() -> new RuntimeException("用户未登录"));

        // 查询订单
        Order order = orderRepository.findOrderById(id);
        if (order == null) {
            return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "订单不存在");
        }

        // 权限验证：直接写在Controller中
        // 1. 用户自己可以查看自己的订单
        boolean isOrderOwner = order.getCustomer().getId().equals(currentUser.getId());

        // 2. 商家可以查看自己店铺的订单
        boolean isBusinessOwner = order.getBusiness() != null &&
                order.getBusiness().getBusinessOwner().getId().equals(currentUser.getId());



        // 如果三种权限都不满足，返回无权访问
        if (!isOrderOwner && !isBusinessOwner ) {
            return HttpResult.failure(ResultCodeEnum.NOT_AUTHORIZED);
        }

        return HttpResult.success(order);
    }

    @GetMapping("")
    @Operation(summary = "返回当前用户订单",method = "GET")
    public  HttpResult listOrdersByUserId(@RequestParam Long userId) throws Exception{

            // 参数校验
            if (userId== null || userId<= 0) {
                return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, "用户ID不能为空且必须大于0");
            }


            // 直接使用Repository查询订单
            List<Order> orders = orderRepository.findByCustomerIdWithDetails(userId);

            return HttpResult.success(orders);


    }

    @PostMapping("/orderState")
    @Operation(summary = "返回订单状态")
    public HttpResult orderState(@RequestParam Long id) throws Exception{
        User currentUser = userService.getUserWithAuthorities()
                .orElseThrow(() -> new RuntimeException("用户未登录"));

        // 2. 查询订单（包含关联实体）
        Order order = orderRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("订单不存在"));

        // 3. 三重权限验证（客户本人/商家/管理员）
        boolean isCustomer = currentUser.getId().equals(order.getCustomer().getId());
        boolean isBusinessOwner = order.getBusiness() != null
                && currentUser.getId().equals(order.getBusiness().getBusinessOwner().getId());


        if (!isCustomer && !isBusinessOwner ) {
            return HttpResult.failure(ResultCodeEnum.NOT_AUTHORIZED);
        }

        // 4. 安全状态流转（示例状态机）
        int currentState = order.getOrderState();
        int newState = currentState + 1;



        order.setOrderState(newState);
        orderRepository.save(order);
        if (order.getCustomer() != null && order.getBusiness() != null) {
            List<Cart> carts = cartRepository.findByCustomerIdAndBusinessId(
                    order.getCustomer().getId(),
                    order.getBusiness().getId()
            );

            carts.forEach(cart -> {
                cart.setQuantity(0);  // 数量清零
                cartRepository.save(cart);  // 更新到数据库
            });

            System.out.println("已清零购物车数量，影响记录数: " + carts.size());
        }




        return HttpResult.success("状态更新成功");
    }


    @GetMapping("/business/current")
    @Operation(summary = "获取当前商家用户的活跃订单",
            description = "查询当前登录商家用户（店主）的所有订单（状态为1或2）")
    public HttpResult<List<Order>> getCurrentBusinessActiveOrders() {
        try {
            // 1. 获取当前登录用户
            User currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录或登录已过期"));

            // 2. 直接查询属于当前商家且状态为1或2的订单（最优方案）
            List<Order> activeOrders = orderRepository.findByBusinessOwnerIdAndOrderStateIn(
                    currentUser.getId(),
                    Arrays.asList(1, 2));

            // 3. 返回结果
            return HttpResult.success(activeOrders);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SYSTEM_ERROR, "获取订单失败: " + e.getMessage());
        }
    }



    @PostMapping("/business/action")
    @Operation(summary = "商家订单操作",
            description = "商家可以接单（状态+1）或取消订单（删除订单）")
    public HttpResult<String> handleOrderAction(
            @RequestParam Long orderId,
            @RequestParam String action) {
        try {
            // 1. 获取当前登录用户
            User currentUser = userService.getUserWithAuthorities()
                    .orElseThrow(() -> new RuntimeException("用户未登录或登录已过期"));

            // 2. 查询订单并验证权限
            Order order = orderRepository.findById(orderId)
                    .orElseThrow(() -> new RuntimeException("订单不存在"));

            // 验证是否是商家所有者
            if (order.getBusiness() == null ||
                    !order.getBusiness().getBusinessOwner().getId().equals(currentUser.getId())) {
                return HttpResult.failure(ResultCodeEnum.NOT_AUTHORIZED, "无权操作此订单");
            }

            // 3. 根据action执行不同操作
            switch (action.toLowerCase()) {
                case "accept":
                    // 接单操作：状态+1
                    order.setOrderState(order.getOrderState() + 1);
                    orderRepository.save(order);
                    return HttpResult.success("接单成功，订单状态已更新");

                case "cancel":
                    // 取消操作：删除订单
                    orderRepository.delete(order);
                    return HttpResult.success("订单已取消");

                default:
                    return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, "无效的操作类型");
            }
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SYSTEM_ERROR, "操作失败: " + e.getMessage());
        }
    }



}

